#include "CompletionPort.h"

CompletionPort::CompletionPort(size_t threads)
{
	m_h = ::CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, 0, threads);
}

CompletionPort::~CompletionPort(void)
{
}

void CompletionPort::Associate( HANDLE file, ULONG_PTR key )
{
	THROW_BAD_BOOL_RET(::CreateIoCompletionPort(file, m_h, key, 0));
}

bool CompletionPort::WaitStatus( size_t& bytes, ULONG_PTR* key, LPOVERLAPPED* overlapped, size_t timeout)
{
	DWORD dwBytes = 0;

	//printf("GetQueuedCompletionStatus m_h:%x, timeout:%i\n", m_h, timeout);
	 if(GetQueuedCompletionStatus(m_h, &dwBytes, key, overlapped, timeout))
	 {
		 //printf("GetQueuedCompletionStatus returned %i bytes\n", bytes);
		 bytes = dwBytes;
		 return true;
	 }
	 //printf("GetQueuedCompletionStatus returned false!\n");
	 return false;
}

void CompletionPort::PostStatus( size_t bytes, ULONG_PTR key, LPOVERLAPPED overlapped )
{
	//printf("Post status m_h:%x bytes:%i, key:%x, overlapped:%x\n", m_h, bytes, key, overlapped);
	THROW_BAD_BOOL_RET(PostQueuedCompletionStatus(m_h, bytes, key, overlapped));
}